using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Magiq.Insert {
    public class QueryableInsert<TSource,TNew> : IInsert {
        private readonly IQueryable<TSource> source;
        private readonly Expression<Func<TSource, TNew>> newExpression;

        public QueryableInsert(IQueryable<TSource> queryable, Expression<Func<TSource, TNew>> newValueExpression) {
            source = queryable;
            newExpression = newValueExpression;
        }

        public int Into<TDestination>(IEnumerable<TDestination> destination) where TDestination : class {
            if (!typeof(TDestination).IsAssignableFrom(typeof(TNew)))
                throw new InvalidOperationException("Type " + typeof(TNew).FullName + " should inherit from " +
                                                    typeof(TDestination).FullName);
            var insert = new InsertIntoQueryable<TSource, TDestination, TNew>(source, newExpression, destination);
            return insert.Execute();
        }
    }
}